import 'package:flutter_app_demo/extension/common.dart';
import 'package:flutter_app_demo/net/api_exception.dart';
import 'package:flutter_app_demo/net/http_agent.dart';
import 'package:flutter_app_demo/utils/logger.dart';
import 'package:go_router/go_router.dart';
import 'package:mvvm_plus/mvvm_plus.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

// Created by 王亮 on 2025/2/8.
class OnePageViewModel extends ViewModel {
  final RefreshController _refreshController =
      RefreshController(initialRefresh: true);

  get refreshController => _refreshController;

  final Map<String, String>? data;

  OnePageViewModel(this.data);

  String paramsContent = "";
  List<Object> articles = [];

  List<String> testListData = [];

  int page = 0;

  get enablePullUp => articles.isNotEmpty;

  @override
  void initState() {
    super.initState();
    var id = data?['id']?.toInt(defaultValue: 0) ?? 0;
    var name = data?['name'] ?? '';

    paramsContent = "id: $id, name: $name";
  }

  void refreshData() {
    page = 0;
    testListData.clear();
    articles.clear();
    _doTestRequest(true);
  }

  void loadData() {
    page++;
    _doTestRequest(false);
  }

  void backWithParams() {
    context.pop('这是返回携带的参数');
  }

  void _doMockRequest(bool isFresh) async {
    int max = 75;
    await Future.delayed(const Duration(seconds: 2));

    if (testListData.length >= max) {
      return;
    }

    for (int i = 0; i < 20; i++) {
      if (testListData.length < max) {
        testListData.add("index ${testListData.length} page: ${page}");
      }
    }

    buildView();

    if (isFresh) {
      _refreshController.refreshCompleted();
    }

    if (testListData.length == max) {
      _refreshController.loadNoData();
    } else {
      _refreshController.loadComplete();
    }
  }

  void _doTestRequest(bool refresh) async {
    try {
      Map<String, dynamic> params = {};
      String urlTemplate = "article/list/{page}/json";
      String url = urlTemplate.replaceAll("{page}", page.toString());
      if (refresh) {
        _refreshController.refreshCompleted();
      }
    } on ApiException catch (exception) {
      Log.e(
          "WLTest error code: ${exception.code}, message: ${exception.message}");
      _refreshController.loadFailed();
    }
  }
}
